<template>
  <AdvancedTable
    ref="tableRef"
    :data="tableData"
    :columns="tableColumns"
    :loading="loading"
    :pagination="pagination"
    :show-view-toggle="true"
    :show-column-settings="true"
    :card-layout="{ xs: 24, sm: 12, md: 8, lg: 6 }"
    row-key="id"
    @refresh="handleRefresh"
    @sort-change="handleSortChange"
    @selection-change="handleSelectionChange"
    @row-click="handleRowClick"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    @view-mode-change="handleViewModeChange"
  >
    <!-- 工具栏左侧 -->
    <template #toolbar-left>
      <el-button 
        v-if="selectedTransactions.length > 0"
        type="danger" 
        :icon="Delete"
        @click="handleBatchDelete"
      >
        批量删除 ({{ selectedTransactions.length }})
      </el-button>
    </template>

    <!-- 工具栏右侧 -->
    <template #toolbar-right>
      <el-button :icon="Download" @click="handleExport">导出</el-button>
    </template>

    <!-- 自定义列插槽 -->
    <template #column-transactionId="{ row }">
      <div class="transaction-id-cell">
        <div class="transaction-id">{{ row.transactionId }}</div>
        <div class="data-source">
          <el-tag 
            v-if="row.dataSource === 'file_import'" 
            size="small" 
            type="primary"
          >
            文件导入
          </el-tag>
          <el-tag 
            v-else-if="row.dataSource === 'plugin_capture'" 
            size="small" 
            type="success"
          >
            插件捕获
          </el-tag>
          <el-tag 
            v-else 
            size="small" 
            type="info"
          >
            API同步
          </el-tag>
        </div>
      </div>
    </template>

    <template #column-transactionDateTime="{ row }">
      <div class="datetime-cell">
        <div class="date">{{ formatDate(row.transactionDate) }}</div>
        <div class="time">{{ formatTime(row.transactionTime) }}</div>
      </div>
    </template>

    <template #column-payerInfo="{ row }">
      <div class="payer-cell">
        <div class="payer-name">{{ row.payerName }}</div>
        <div class="payer-account" v-if="row.payerAccount">
          {{ maskAccount(row.payerAccount) }}
        </div>
        <div class="bank-name" v-if="row.bankName">
          <el-icon><OfficeBuilding /></el-icon>
          {{ row.bankName }}
        </div>
      </div>
    </template>

    <template #column-amount="{ row }">
      <div class="amount-cell">
        <span 
          class="amount" 
          :class="{ 'income': row.amount > 0, 'expense': row.amount < 0 }"
        >
          {{ formatCurrency(row.amount) }}
        </span>
        <div 
          v-if="row.balance" 
          class="balance"
          :title="`交易后余额: ${formatCurrency(row.balance)}`"
        >
         余额: {{ formatCurrency(row.balance) }}
        </div>
      </div>
    </template>

    <template #column-matchStatus="{ row }">
      <MatchStatusBadge 
        :status="row.matchStatus"
        :order="row.matchedOrder"
        @click-match="() => handleMatchClick(row)"
      />
    </template>

    <template #column-filterStatus="{ row }">
      <FilterStatusBadge 
        :filtered="row.isFiltered"
        :reason="row.filterReason"
        @click-filter="() => handleFilterClick(row)"
      />
    </template>

    <template #column-remark="{ row }">
      <div class="remark-cell">
        <el-tooltip v-if="row.remark" :content="row.remark" placement="top">
          <span class="remark-text">{{ truncateText(row.remark, 20) }}</span>
        </el-tooltip>
        <span v-else class="no-remark">无备注</span>
      </div>
    </template>

    <template #column-smartAnalysis="{ row }">
      <SmartAnalysis 
        :transaction="row" 
        @analysis-action="handleAnalysisAction" 
      />
    </template>

    <template #column-importInfo="{ row }">
      <div class="import-info">
        <div class="import-batch" v-if="row.importBatch">
          {{ row.importBatch }}
        </div>
        <div class="import-time">
          {{ formatRelativeTime(row.createdAt) }}
        </div>
      </div>
    </template>

    <!-- 操作列 -->
    <template #column-actions="{ row }">
      <div class="action-buttons">
        <el-button 
          type="primary" 
          link 
          :icon="View" 
          @click.stop="showTransactionDetail(row)"
        >
          详情
        </el-button>
        
        <el-button 
          type="success" 
          link 
          :icon="Connection" 
          @click.stop="handleManualMatch(row)"
          v-if="!row.isFiltered && !row.matchedOrder"
        >
          手动匹配
        </el-button>
        
        <el-button 
          type="warning" 
          link 
          :icon="Edit" 
          @click.stop="editTransaction(row)"
        >
          编辑
        </el-button>
        
        <el-dropdown 
          @command="(command) => handleMoreAction(command as string, row)"
          @click.stop
        >
          <el-button type="info" link :icon="More" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item 
                command="filter" 
                :icon="Filter"
                v-if="!row.isFiltered"
              >
                标记过滤
              </el-dropdown-item>
              <el-dropdown-item 
                command="unfilter" 
                :icon="CircleCheck"
                v-else
              >
                取消过滤
              </el-dropdown-item>
              <el-dropdown-item command="duplicate" :icon="CopyDocument">
                标记重复
              </el-dropdown-item>
              <el-dropdown-item command="export" :icon="Download">
                导出单条
              </el-dropdown-item>
              <el-dropdown-item 
                command="delete" 
                :icon="Delete"
                divided
              >
                删除流水
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </template>

    <!-- 卡片视图插槽 -->
    <template #card="{ row, index }">
      <SingleTransactionCard 
        :transaction="row"
        :get-data-source-type="getDataSourceType"
        :get-data-source-text="getDataSourceText"
        :get-match-status-type="getMatchStatusType"
        :get-match-status-text="getMatchStatusText"
        :format-currency="formatCurrency"
        :format-date="formatDate"
        :truncate-text="truncateText"
        :icons="icons"
        @card-click="showTransactionDetail"
        @match-status-click="handleMatchClick"
        @manual-match="handleManualMatch"
        @edit="editTransaction"
        @more-action="(command, transaction) => handleMoreAction(command, transaction)"
      />
    </template>
  </AdvancedTable>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  View, Edit, Delete, More, Filter, Connection, 
  Download, CopyDocument, CircleCheck, OfficeBuilding
} from '@element-plus/icons-vue'
import AdvancedTable from '@/components/AdvancedTable.vue'
import MatchStatusBadge from './MatchStatusBadge.vue'
import FilterStatusBadge from './FilterStatusBadge.vue'
import SmartAnalysis from './SmartAnalysis.vue'
import TransactionCard from './TransactionCard.vue'
import SingleTransactionCard from './SingleTransactionCard.vue'

// 图标对象
const icons = {
  View,
  Edit,
  Delete,
  More,
  Filter,
  Connection,
  Download,
  CopyDocument,
  CircleCheck,
  OfficeBuilding
}

// 定义props
interface Props {
  tableData: any[]
  loading: boolean
  pagination: any
  selectedTransactions: any[]
}

const props = withDefaults(defineProps<Props>(), {
  tableData: () => [],
  loading: false,
  pagination: () => ({}),
  selectedTransactions: () => []
})

// 定义emits
const emit = defineEmits<{
  (e: 'refresh'): void
  (e: 'sort-change', sort: { prop: string; order: string }): void
  (e: 'selection-change', selection: any[]): void
  (e: 'size-change', size: number): void
  (e: 'current-change', page: number): void
  (e: 'view-mode-change', mode: 'table' | 'card'): void
  (e: 'view-detail', transaction: any): void
  (e: 'manual-match', transaction: any): void
  (e: 'edit', transaction: any): void
  (e: 'filter', transaction: any): void
  (e: 'delete', transaction: any): void
  (e: 'export'): void
  (e: 'batch-delete'): void
  (e: 'analysis-action', analysis: any): void
}>()

// 响应式数据
const tableRef = ref()

// 表格列配置
const tableColumns = computed(() => [
  { type: 'selection', width: 50 },
  { 
    prop: 'transactionId', 
    label: '流水号', 
    width: 180, 
    fixed: true,
    slot: 'column-transactionId'
  },
  { 
    prop: 'transactionDateTime', 
    label: '交易时间', 
    width: 160, 
    sortable: true,
    slot: 'column-transactionDateTime'
  },
  { 
    prop: 'payerInfo', 
    label: '付款方信息', 
    minWidth: 200,
    slot: 'column-payerInfo'
  },
  { 
    prop: 'amount', 
    label: '交易金额', 
    width: 130, 
    align: 'right',
    sortable: true,
    slot: 'column-amount'
  },
  { 
    prop: 'matchStatus', 
    label: '匹配状态', 
    width: 120,
    slot: 'column-matchStatus'
  },
  { 
    prop: 'filterStatus', 
    label: '过滤状态', 
    width: 120,
    slot: 'column-filterStatus'
  },
  { 
    prop: 'remark', 
    label: '交易备注', 
    minWidth: 150,
    slot: 'column-remark'
  },
  { 
    prop: 'smartAnalysis', 
    label: '智能分析', 
    width: 150,
    slot: 'column-smartAnalysis'
  },
  { 
    prop: 'importInfo', 
    label: '导入信息', 
    width: 140,
    slot: 'column-importInfo'
  },
  { 
    prop: 'actions', 
    label: '操作', 
    width: 250, 
    fixed: 'right',
    slot: 'column-actions'
  }
])

// 方法
const handleRefresh = () => {
  emit('refresh')
}

const handleSortChange = (sort: { prop: string; order: string }) => {
  emit('sort-change', sort)
}

const handleSelectionChange = (selection: any[]) => {
  emit('selection-change', selection)
}

const handleSizeChange = (size: number) => {
  emit('size-change', size)
}

const handleCurrentChange = (page: number) => {
  emit('current-change', page)
}

const handleViewModeChange = (mode: 'table' | 'card') => {
  emit('view-mode-change', mode)
}

const handleRowClick = (row: any) => {
  console.log('点击行:', row)
}

const showTransactionDetail = (transaction: any) => {
  emit('view-detail', transaction)
}

const handleManualMatch = (transaction: any) => {
  emit('manual-match', transaction)
}

const editTransaction = (transaction: any) => {
  emit('edit', transaction)
}

const handleMatchClick = (transaction: any) => {
  if (transaction.matchedOrder) {
    // 跳转到对账结果页面
    console.log('跳转到对账结果页面')
  } else {
    handleManualMatch(transaction)
  }
}

const handleFilterClick = (transaction: any) => {
  emit('filter', transaction)
}

const handleMoreAction = (command: string, transaction: any) => {
  switch (command) {
    case 'filter':
    case 'unfilter':
      handleFilterClick(transaction)
      break
    case 'duplicate':
      markAsDuplicate(transaction)
      break
    case 'export':
      exportSingleTransaction(transaction)
      break
    case 'delete':
      deleteTransaction(transaction)
      break
  }
}

const markAsDuplicate = (transaction: any) => {
  console.log('标记为重复流水:', transaction)
  ElMessage.success('已标记为重复流水')
}

const exportSingleTransaction = (transaction: any) => {
  console.log('导出单条流水:', transaction)
  ElMessage.success('导出成功')
}

const deleteTransaction = (transaction: any) => {
  ElMessageBox.confirm('确定要删除这条流水记录吗？', '删除流水', {
    type: 'warning'
  }).then(() => {
    emit('delete', transaction)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

const handleBatchDelete = () => {
  if (props.selectedTransactions.length === 0) {
    ElMessage.warning('请先选择流水')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${props.selectedTransactions.length} 条流水记录吗？`, 
    '批量删除', 
    { type: 'warning' }
  ).then(() => {
    emit('batch-delete')
    ElMessage.success('批量删除成功')
  }).catch(() => {
    // 取消删除
  })
}

const handleExport = () => {
  emit('export')
}

const handleAnalysisAction = (analysis: any) => {
  emit('analysis-action', analysis)
}

// 工具函数
const formatCurrency = (amount: number) => {
  const absAmount = Math.abs(amount)
  const sign = amount >= 0 ? '' : '-'
  return sign + '¥' + absAmount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const formatDate = (date: string) => {
  if (!date) return '';
  const dateObj = new Date(date);
  if (isNaN(dateObj.getTime())) return '无效日期';
  return dateObj.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  });
}

const formatTime = (time: string) => {
  if (!time) return '';
  const timeObj = new Date(time);
  if (isNaN(timeObj.getTime())) return '无效时间';
  return timeObj.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const formatRelativeTime = (timestamp: string) => {
  const now = new Date()
  const past = new Date(timestamp)
  const diffMs = now.getTime() - past.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return `${Math.floor(diffDays / 7)}周前`
  }
}

const maskAccount = (account: string) => {
  if (account.length <= 8) return account
  return account.substring(0, 4) + '****' + account.substring(account.length - 4)
}

const truncateText = (text: string, maxLength: number) => {
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

const getDataSourceType = (dataSource: string) => {
  const typeMap: Record<string, string> = {
    'file_import': 'primary',
    'plugin_capture': 'success',
    'api_sync': 'info'
  }
  return typeMap[dataSource] || 'info'
}

const getDataSourceText = (dataSource: string) => {
  const textMap: Record<string, string> = {
    'file_import': '文件导入',
    'plugin_capture': '插件捕获',
    'api_sync': 'API同步'
  }
  return textMap[dataSource] || '未知来源'
}

const getMatchStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    'matched': 'success',
    'pending': 'warning',
    'unmatched': 'info'
  }
  return typeMap[status] || 'info'
}

const getMatchStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    'matched': '已匹配',
    'pending': '待确认',
    'unmatched': '未匹配'
  }
  return textMap[status] || '未知状态'
}

</script>

<style scoped lang="scss">
.transaction-id-cell {
  .transaction-id {
    font-family: 'Monaco', 'Consolas', monospace;
    font-size: 12px;
    color: #606266;
    margin-bottom: 4px;
  }
}

.datetime-cell {
  .date {
    font-weight: 500;
    margin-bottom: 2px;
  }
  
  .time {
    font-size: 12px;
    color: #909399;
  }
}

.payer-cell {
  .payer-name {
    font-weight: 500;
    margin-bottom: 4px;
  }
  
  .payer-account {
    font-size: 12px;
    color: #909399;
    margin-bottom: 4px;
  }
  
  .bank-name {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: #909399;
  }
}

.amount-cell {
  .amount {
    font-weight: 600;
    
    &.income {
      color: #52c41a;
    }
    
    &.expense {
      color: #f5222d;
    }
  }
  
  .balance {
    font-size: 11px;
    color: #909399;
    margin-top: 2px;
  }
}

.remark-cell {
  .remark-text {
    color: #606266;
  }
  
  .no-remark {
    color: #c0c4cc;
    font-style: italic;
  }
}

.import-info {
  .import-batch {
    font-size: 12px;
    color: #606266;
    margin-bottom: 2px;
  }
  
  .import-time {
    font-size: 11px;
    color: #909399;
  }
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>